package com.wl.boot.batch.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @title：
 * @author: mengchaob
 * @date: 2021年08月18日 23:57
 * @description:
 */
public class MyBatisUtils {

    public static final String CONFIG_FILENAME = "mybatis-config.xml";
    //使用ThreadLocal保存SQLSession对象
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    //SqlSession的工厂，单例
    private static SqlSessionFactory factory = null;

    /**

     * 创建工厂

     */

    public static void buildFactory(){
        try {
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(CONFIG_FILENAME));

        } catch (IOException e) {
            e.printStackTrace();

        }

    }

//在静态代码块中执行，保证工厂的创建只执行一次

    static{
        buildFactory();
    }

    /**

     * 从当前线程中获得Session

     * @return

     */

    public static SqlSession getSession(){
        //从ThreadLocal获得线程中的SqlSession
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            //如果SqlSession为空，创建SqlSession
            if(factory == null){
                buildFactory();

            }
            sqlSession = factory.openSession();
            //把新创建的SqlSession，存入到ThreadLocal,绑定到线程中
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtils.getSession();

    }

    /**

     * 关闭Session

     */

    public static void closeSession(){
        //从ThreadLocal获得线程中的SqlSession
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            //关闭会话
            sqlSession.close();
            //设置为null，gc会尽快回收
            sqlSession = null;
            //删除掉ThreadLocal中的SqlSession
            threadLocal.set(null);
        }

    }
}
